package xddq

import (
	"compress/gzip"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	nurl "net/url"
	"strings"
	"time"
	D "websocket_apn/define"
	"websocket_apn/log"
	"websocket_apn/proto"
	http_transport "websocket_apn/transfer/net/http"

	"github.com/google/uuid"
)

type PwdLoginData struct {
	AppPst    string      `json:"app_pst"`
	Gxid      string      `json:"gxid"`
	Xncd      string      `json:"xncd"`
	Smerr     string      `json:"smerr"`
	TextSmerr string      `json:"text_smerr"`
	Xwsm      string      `json:"xwsm"`
	UserInfo  interface{} `json:"userinfo"`
}
type PwdLoginRsp struct {
	Code int          `json:"code"`
	Data PwdLoginData `json:"data"`
	Msg  string       `json:"msg"`
}
type PhoneLoginUserInfo struct {
	LoginAccount string `json:"login_account"`
	Uid          int    `json:"uid"`
	IsOldUser    int    `json:"is_old_user"`
}
type PhoneLoginData struct {
	AppPst   string             `json:"app_pst"`
	UserInfo PhoneLoginUserInfo `json:"userinfo"`
	Pdata    string             `json:"pdata"`
	Myrn     int                `json:"myrn"`
	Xwsm     string             `json:"xwsm"`
	Xfcn     string             `json:"xfcn"`
	Swtxt    string             `json:"swtxt"`
	Swcot    string             `json:"swcot"`
	Swal     string             `json:"swal"`
}
type PhoneLoginRsp struct {
	Code int            `json:"code"`
	Data PhoneLoginData `json:"data"`
	Msg  string         `json:"msg"`
}

type ServerListData struct {
	ServerId    int    `json:"serverId"`    //
	LabelName   string `json:"labelName"`   //
	ServerName  string `json:"serverName"`  //区服名称
	Address     string `json:"address"`     //服务器地址
	ServerState int    `json:"serverState"` //
	ServerType  int    `json:"serverType"`  //
	OpenTime    int    `json:"openTime"`    //开服时间
	New         bool   `json:"new"`         //是否是新服
}

type ServerListRsp struct {
	ServerList          []ServerListData `json:"serverList"` //区服列表
	PlayerServerList    []int            `json:"playerServerList"`
	Notice              interface{}      `json:"notice"`
	Works               string           `json:"works"`               //
	RecommendServerId   int              `json:"recommendServerId"`   //
	LabelNameList       []string         `json:"labelNameList"`       //
	ConfigVersion       string           `json:"configVersion"`       //
	ActivitySceneSwitch string           `json:"activitySceneSwitch"` //
	FestivalSceneSwitch string           `json:"festivalSceneSwitch"` //
	TimeZone            int              `json:"timeZone"`            //
	ServerTime          int              `json:"serverTime"`          //服务器时间
	BackendConfigMap    interface{}      `json:"backendConfigMap"`
	Audit               bool             `json:"audit"` //
}

type TokenReqData struct {
	AppID    string `json:"appID"`    //
	GameId   string `json:"gameId"`   //
	Pid      string `json:"pid"`      //
	ClientId string `json:"clientId"` //
	Oaid     string `json:"oaid"`     //
	SqGameId string `json:"sqGameId"` //
	Token    string `json:"token"`    //
	Uid      string `json:"uid"`      //
	Uname    string `json:"uname"`    //
	Time     string `json:"time"`     //
}

type TokenWxReqData struct {
	AppDomain       string `json:"app_domain"`       //
	AppExt          string `json:"app_ext"`          //
	AppId           string `json:"appid"`            //
	GameId          int    `json:"game_id"`          //
	Guid            string `json:"guid"`             //
	IdVerify        int    `json:"id_verify"`        //
	IdVerifySwitch  int    `json:"id_verify_switch"` //
	IsAdult         int    `json:"is_adult"`         //
	IsTg            int    `json:"is_tg"`            //
	Nickname        string `json:"nickname"`         //
	Openid          string `json:"openid"`           //
	Referer         string `json:"referer"`          //
	SharedSwitch    string `json:"shared_switch"`    //
	Sign            string `json:"sign"`             //
	SubscribeSwitch string `json:"subscribe_switch"` //
	Time            int64  `json:"nickname"`         //
	Uid             int    `json:"uid"`              //
	UnionId         string `json:"unionid"`          //
	WxIsSubscribe   int    `json:"wx_is_subscribe"`  //
}
type LoginInfo struct {
	DeviceInfo     string //未加密的设备信息
	Ptoken         string //相当于密码 https://apimyh5.37.com/index.php?c=sdk-login&a=act_login
	Puid           string //手机号
	Pwd            string //密码
	Account        int    //指定账号登录
	PhoneLoginData PhoneLoginData
	ServerList     ServerListData //服务器信息
	TokenReqData   TokenReqData
	UserInfo       D.UserInfo
}

func encryptPwd(pwd string) string {
	if pwd == "" {
		return ""
	}
	// Construct the new string
	str := proto.GetRandomNum(8) + pwd[:3] + proto.GetRandomNum(5) + pwd[3:] + proto.GetRandomNum(2)

	// Encode the string using Base64
	base64Str := base64.StdEncoding.EncodeToString([]byte(str))
	return strings.TrimSpace(base64Str)
}

/*{
	"code": 1,
	"msg": "登录成功。",
	"data": {
		"app_pst": "YTM0NUkxdmtldFpPQW8wejllTG1uc2M0Vm9YRXMycUM4bS9vcVJLTFVBR1oxb1pEQlo4VG9QMWRDQjRhL2gxa1pneTVqYllraEdoKzBRU1luQXdaODRNWkVDOVB6YlRXVUx4VU55ZGtZRlJpekJoVCtPekpzSzAzWW1TZVE2N0N1MXRjdS8rQ20wRWlFK3MrVVkzSEdoc0ltQ0VmOSs0dXdlalF4ejFWa3hzMVVnbllpZGM2d3M4SFhFUWlIODZjMFRqWFFBUUdsd0w4YVl5SjNrczQ5Mm4yTkhMUjRYYUt5VG9oNFB5UEJn",
		"gxid": "GUID66f6c3a4d4cda223793640011256",
		"xncd": "L1EwWnZOL0l0cTNrOHU3N0R1RTQ1SXExajAxOEhhNFUySkpPNk9xS0EwdzRyak4xYzA3SHhQNGNvSnJybEM5VGZCczgxdGRlYkVPVzZFMDFabGdSMDdKTkxwTVR0bllvWHRGNm9KalJ2NTUyRXRlRmx5U1pZbllQcUk0bA==",
		"smerr": "0",
		"text_smerr": "",
		"xwsm": "0",
		"userinfo": {
			"login_account": "19969795984",
			"uid": "2532158588",
			"show_account": "19969795984",
			"for_show": {
				"VIP_DEEP": 1,
				"VIP_EXP": 302,
				"VIP_UPPER": 600,
				"IS_CHECK_ID_CARD": 1,
				"IS_BIND_ALIAS": 1,
				"IS_YOUKE": 1,
				"IS_PHONE_BIND": 1,
				"IS_EMAIL_BIND": 0,
				"IS_QUESTION_BIND": 0,
				"IS_ADULT": 1,
				"IS_REAL_ADULT": 1,
				"ID_CARD_NUMBER": "4****************1",
				"NAME": "**华",
				"SHOW_NAME": "19969795984"
			}
		}
	}
}*/
//账号密码登录
func LoginByPwd(loginInfo *LoginInfo) *PwdLoginRsp {
	log.Infof("开始使用密码登录账号")
	currentTime := fmt.Sprintf("%d", time.Now().Unix())
	deviceInfoBytes := []byte("IC=1|DF=android|OS=7.1.2|AT=" + currentTime + "|DC=10e89a8141283233ac839de555d75040|PM=V2304A|PMN=|BW=|AC=db68059c-80f1-483d-91c6-7d8a28b1ef66|RL=1440x3200|PN=com.global.xddq.t3p|PV=2.4.00|SDKV=4.6.8|IDFA=|ADID=21679c4d7fa2d0376b80029d6e7d7a69|UEADID=483de43b6e70a2df|IMEI=|OAID=|SDK_RF=hajrttss_g1_android_xdb|SDK_RFP=33101765|SDK_ADP=40351apk|CHANNEL_ID=")
	loginInfo.DeviceInfo = string(deviceInfoBytes)
	tjH5tg := "h5zy|h503|" + base64.StdEncoding.EncodeToString(deviceInfoBytes)
	rspData := &PwdLoginRsp{}
	head := http.Header{}
	url := "https://mysdk.37.com/index.php?c=api-login&a=act_login"
	method := "POST"
	post := "PACKAGE_VERSION=2.4.00&MAC=020000000000&BROWSER=&PLAT_FORM=h5sdk&tj_from=800&TJ_SGID=android.game.xddq_ttss1&SDK_JRTT_APPKEY=c92f40cbde5779eacee61d7df38eaeba&" +
		"TJ_FPFM=h5sdk&IMEI=&SDK_JRTT_APPID=535996&CPU_ABI=%5Barm64-v8a%5D&OAID=&MEMORY_TOTAL=12G&FS_SIZE_TOTAL=238.7G&SDK_IS_JRTT=1&LANGUAGE=zh&AD_TYPE=&NET_TYPE=WIFI&" +
		"img_code=&AD_PARAM=40351apk&PACKAGE_NAME=com.global.xddq.t3p&TJ_ADT=&sub_game_id=android.game.xddq_ttss1&PHONEMF=vivo&appid=913&REFERER_TYPE=h503&OS_VERSION=7.1.2&" +
		"SDK_JRTT_APPNAME=xddq_ttss&bid=21286&TJ_ADP=40351apk&TJ_REFR=hajrttss_g1_android_xdb&SUB_GAME_ID=android.game.xddq_ttss1&REFERER_PARAM=33101765&" +
		"APPS=1727447817964-3192601368261310121&PUBLISH_PLATFORM=&TJ_LID=&CHANNEL_ID=&s=1&game_server_id=&ad_type=&TJ_REFRP=33101765&BID=21286&REFERER=hajrttss_g1_android_xdb&" +
		"callback=&img_ver=1.0&SDK_VERSION=4.6.8&UEANDROIDID=483de43b6e70a2df&referer=hajrttss_g1_android_xdb&DEVICE_CODE=10e89a8141283233ac839de555d75040&RESOLUTION=1440x3200&" +
		"img_equipment=10e89a8141283233ac839de555d75040&TJ_BID=21286&ad_param=40351apk&lid=&PHONE_MODEL=V2304A&LID=0&ANDROIDID=21679c4d7fa2d0376b80029d6e7d7a69&" +
		"ACTIVATION_CODE=db68059c-80f1-483d-91c6-7d8a28b1ef66&TJ_GSID=&THIRD_PLATFORM=&GAME_ID=913&password=" + encryptPwd(loginInfo.Pwd) + "&IDFA=&PT_CODE=h5zy&" +
		"tj_way=1&LAUNCH_TIME=" + currentTime + "&clientid=db68059c-80f1-483d-91c6-7d8a28b1ef66&tj_h5tg=" + nurl.QueryEscape(tjH5tg) +
		"&login_account=" + loginInfo.Puid + "&ajax=1&TJ_GID=913&PHONE_MODEL_NAME=&ext=&PHONEBRAND=vivo&DEVICEFORM=android&ACTIVATION_TIME=" + currentTime +
		"&game_id=913&save_state=1&IS_FIRSTLAUNCH=1&LAUNCH_GAME=913"
	head.Add("Content-Type", "application/x-www-form-urlencoded")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	head.Add("Host", "mysdk.37.com")
	head.Add("Connection", "Keep-Alive")
	head.Add("Accept-Encoding", "gzip")
	head.Add("User-Agent", "okhttp/3.12.12")
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("LoginByPwd error: %s", err.Error())
		return nil
	}
	defer resp.Body.Close()
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("LoginByPwd read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("LoginByPwd read body error: %s\n", err.Error())
			return nil
		}
	}
	//log.Debugf("head:%#v\n", resp.Header)
	log.Debugf("%s", string(reapData))
	err = json.Unmarshal(reapData, rspData)
	if err != nil {
		log.Errorf("LoginByPwd Unmarshal body error: %s\n", err.Error())
		return nil
	}
	if rspData.Code != 1 {
		log.Errorf("登录失败 code %d, %s\n", rspData.Code, rspData.Msg)
		return nil
	}
	log.Debugf("LoginByPwd:%+v\n", rspData)
	loginInfo.Ptoken = rspData.Data.AppPst
	return rspData
}

/*{
	Code:1
	Data:{
		AppPst:ZTQ2NFdpUWdKS1Y2ZVZ3KzgyY1JSRXoyZVJwQ2o0cXVleWV4WEozNm9xRnRHclRlQWIxT0VWMi9CUnJ2TkpYVFpmdjlNU2lHNTVMKy9vSndRU214cW5vSGJRaVhwRXVFUHEyaStMaVRnd2xoYlFtZkRqUE9jWHhlbE96bkt6UGhKc1pDWWdKM2JhSHR6V1dLbUhiY0RrQkNWN1U2ZFhuN3ltb0FUMWhIaWUvc0tBMld6M3lTRzBZblp3TjJkVlZkL0FkeDlJZEcrb0RXYXRGM0UrNlVnNUp1NmdIcHVzaTlBbTBJUGFwNFQ2SXlndUE=
		UserInfo:{
			LoginAccount:h5yx_28f38468
			Uid:2532158588
			IsOldUser:1
		}
		Pdata:
		Myrn:1
		Xwsm:0
		Xfcn:0
		Swtxt:
		Swcot:
		Swal:
	}
	Msg:登录成功
}*/
//账号密码登录
func LoginByPhone(loginInfo *LoginInfo) *PhoneLoginRsp {
	log.Infof("开始登录账号")
	currentTime := fmt.Sprintf("%d", time.Now().Unix())
	deviceInfoBytes := []byte(loginInfo.DeviceInfo)
	deviceInfo := base64.StdEncoding.EncodeToString(deviceInfoBytes)
	rspData := &PhoneLoginRsp{}
	head := http.Header{}
	url := "https://apimyh5.37.com/index.php?c=sdk-login&a=act_login"
	method := "POST"
	post := "browser=&pkgVersionCode=10165&ad_type=&c_game_id=android.game.xddq_ttss1&guid=d6e1971e-47b9-4f0e-b572-472d6ab9f0c3&pt_type=2&tj_from=501&referer=hajrttss_g1_android_xdb&timestamp=" + currentTime + "&pkgVersionName=2.1.00&app_param=jhsdk&gid=223&phone_model_name=&sdkVersion=3.17.1&ad_param=40351apk&lid=&referer_param=33101765&device_plate=android&nettype=WIFI&os_sdk_code=25&pid=37h5&sub_game_id=android.game.xddq_ttss1&pt_code=h5yx&dev=8c79f8642ce7cd63f9c744b94474b583&deviceType=1&device_info=" + deviceInfo + "&bid=21286&referer_type=h503&tj_way=1&ptoken=" + loginInfo.Ptoken + "&sq_game_id=913&fx_c_game_id=23455&is_self=1&puid=" + loginInfo.Puid + "&phone_model=V2304A&pkgName=com.global.xddq.t3p&ip=0.0.0.0&os_version=7.1.2&game_id=223"
	head.Add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	head.Add("Host", "apimyh5.37.com")
	head.Add("Connection", "Keep-Alive")
	head.Add("Accept-Encoding", "gzip")
	head.Add("User-Agent", "okhttp/3.12.12")
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("LoginByPhone error: %s", err.Error())
		return nil
	}
	defer resp.Body.Close()
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("LoginByPhone read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("LoginByPhone read body error: %s\n", err.Error())
			return nil
		}
	}
	//log.Debugf("head:%#v\n", resp.Header)
	log.Debugf("%s", string(reapData))
	err = json.Unmarshal(reapData, rspData)
	if err != nil {
		log.Errorf("LoginByPhone Unmarshal body error: %s\n", err.Error())
		return nil
	}
	if rspData.Code != 1 {
		log.Errorf("登录失败 code %d, %s\n", rspData.Code, rspData.Msg)
		return nil
	}
	log.Debugf("GetLoginToken:%+v\n", rspData)
	return rspData
}

/*
获取服务器列表
POST https://login-xddq-cn.ap3615.com/server/list HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1.2; V2304A Build/N2G47H)
Host: login-xddq-cn.ap3615.com
Connection: Keep-Alive
Content-Length: 172

{"openId":"2532158588","clientVersion":"2.2.00.10177","pFullVersion":"2.1.00.10165","platform":"android","channelId":31,"urlType":"mainLandAppUrl","packageMark":"31003001"}

HTTP/1.1 200
Server: nginx
Date: Sun, 05 May 2024 11:45:48 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: *
Content-Length: 7444

{"serverList":[{"serverId":3109673,"labelName":"风崖山","serverName":"风崖山13服","address":"https://dq31-s9673.ap3615.com/s3109673_http","serverState":1,"serverType":0,"openTime":1712308980000,"new":false},{"serverId":3105209,"labelName":"琼宇山","serverName":"琼宇山9服","address":"https://dq31-s5209.ap3615.com/s3105209_http","serverState":1,"serverType":0,"openTime":1701598921000,"new":false},{"serverId":3105799,"labelName":"禄存山","serverName":"禄存山19服","address":"https://dq31-s5799.ap3615.com/s3105799_http","serverState":1,"serverType":0,"openTime":1703561701000,"new":false},{"serverId":3110454,"labelName":"忘忧山","serverName":"忘忧山14服","address":"https://dq31-s10454.ap3615.com/s3110454_http","serverState":1,"serverType":0,"openTime":1714908240000,"new":true},{"serverId":3110453,"labelName":"忘忧山","serverName":"忘忧山13服","address":"https://dq31-s10453.ap3615.com/s3110453_http","serverState":1,"serverType":0,"openTime":1714908240000,"new":true},{"serverId":3109700,"labelName":"玄蔓山","serverName":"玄蔓山20服","address":"https://dq31-s9700.ap3615.com/s3109700_http","serverState":1,"serverType":0,"openTime":1712371020000,"new":false},{"serverId":3110451,"labelName":"忘忧山","serverName":"忘忧山11服","address":"https://dq31-s10451.ap3615.com/s3110451_http","serverState":1,"serverType":0,"openTime":1714904100000,"new":true}],"playerServerList":[3109700,3109673,3105799,3105209],"notice":{"channelId":0,"language":null,"workPlatform":"","content":"{{color=141717 &#39;}}#    小小妖怪欲登仙，千年修炼化瞬间。仙树法宝增修行，游历四海修大道。一梦醒来，又见修为长矣！{{/color}}\n{{color=ff3737 &#39;}}#    位面交汇！来自“凡人修仙传”奇幻碰撞已开启，化形之宝意外落下，请妥善运用{{/color}}\n{{color=ff3737 &#39;}}#    最新服已于今日开启，前往微信公众号“寻道大千”领礼包，看攻略，助力飞升{{/color}}\n{{color=141717 &#39;}}#【开服活动】\n“登录福利”领[韩立]形象\n“七日签到”奇珍异兽待君领\n“开服庆典”珍稀资源免费换\n“运势”逆天改命降灵兽\n“遗迹争霸”群妖争霸谁敢挡\n“关卡冲榜”战力无双，横压一世\n“首充特惠”获取限定装备、精怪、灵兽{{/color}}\n{{color=141717 &#39;}}#【联系官方】\n1、微信公众号搜索“xddqsy”领取关注礼包，了解更多精彩内容；\n2、游戏内点击左上角头像-客服，进行会话并提交反馈；\n道友的反馈我们都会认真评估，并对问题进行整理优化。{{/color}} \n{{color=141717 &#39;}}#【防诈骗公告】\n道友们修仙渡劫时，需提高警惕，仔细甄别以下常规的骗术套路，谨防受骗：\n1、[世界聊天等发布买卖信息]在世界聊天以“送稀有道具、稀有装备、充值折扣、游戏代练”等为噱头，引导玩家添加QQ、微信诈骗，以及在世界聊天上发布买卖信息的行为都会进行永久封号；\n2、[世界聊天等发布充值福利]在世界聊天以“福利号、免费领取XX充值”等噱头，引导玩家添加QQ、微信诈骗等行为都会进行永久封号；\n3、[妖盟]在盟内引导线下群，进行其他游戏宣传或第三方充值渠道等引导，一经发现都会进行永久封号；\n请道友们切勿尝试。{{/color}}\n{{color=141717 &#39;}}#【4月29日 更新公告】\n1.联动《凡人修仙传》的世界，将跟随韩立的脚步展开一段绮丽的冒险，收获奇珍异宝，敬请期待；\n2.新增四圣宝域活动；道友可与妖盟成员共同探索宝域，开启丰厚宝藏，共筑妖盟荣誉；\n3.新增镇魔玩法；在镇魔的天地之中，除了要镇压蠢蠢欲动的魔物，还要时刻提防躲在阴影之后准备偷袭的敌对妖盟；\n4.为了妖盟发展，开启妖盟悬赏玩法；成员均可接取悬赏任务，需要一定时间后即可自动完成获得丰厚奖励。悬赏期间还可挑战其他妖盟成员获得奖励，敬请期待；\n5.新增召唤神龙活动；道友可召唤各种萌兽，相同的萌兽可合成高级萌兽，最终谁能合成龙神珠领取大奖呢？\n6.新增宗门大比活动；开启后道友可通过出师获得领悟属性，或结伴获得结伴领悟属性，通过计算领悟属性涨幅决定道友的排名，并发放排名奖励；\n7.新增座驾注灵玩法；道友可消耗注灵晶石对座驾进行注灵，每次注灵将随机为座驾带来各种强化效果；\n8.新增跨服斗法玩法(5月6日开启)；开启后可与来自不同位面的道友切磋，同时可获得更丰富的榜单奖励；\n9.新增宗门私聊功能；弟子结伴达到一定次数，即可成为道友，并可互相赠礼，还可以进行私聊；\n10.新增蟠桃宴玩法；拥有宴会邀请帖的道友可开设宴会，邀请参与宴会共同获得赴宴奖励；\n11.新增灵兽内丹轮回殿；敬请关注各位面开启的时间；\n\n【优化内容】\n1.优化灵兽放生和吞噬时，一星以上灵兽需等待倒计时结束才能放生或吞噬；\n2.优化宗门内的任命操作，宗门弟子可以对每个分身进行分别任命；\n3.优化宗门弟子发送全服/跨服请求时候，可以设定对方最低等级要求；\n4.优化宗门出师操作，有多个宗门弟子可以同时出师时候，无需操作即可连续出师；\n5.优化宗门内收到请求的数量，每个道友收到指定请求上限提升到20个；\n6.优化使用不同的分身，可以保存不同的造型；\n7.优化宝箱内法宝信息展示，在宝箱中展示信息时，将同步展示法宝的羁绊，同时也将展示法宝满级后的效果；\n8.优化问道大会中道友分数数据的获取，确保战斗的公平性；\n9.新增仙官送福不再提示的选项；\n10.新增聊天时，长按对方头像，会增加将目标道友@到聊天栏里的功能；\n11.新增天道阁新形象死亡金钩和孔雀女王可供兑换，敬请关注各位面开启的时间；\n12.新增星宿商店内奎木狼、尾火虎、箕水豹的幻化造型购买，还请注意这些造型的有效时间；\n13.增加妖盟活动汇总入口；妖盟对决、九幽争霸、妖盟夺位战、镇魔的活动入口将会合并进妖盟活动的入口内；\n14.新增神通一键突破功能，在拥有一定数量的神通后解锁；\n15.福地新增一键召回派遣出去的鼠宝功能，当派遣出去的鼠宝多余一个时出现；\n16.新增妖邪讨伐的怪物——牛魔；{{/color}}","title":"一斧在手 修仙无忧","tishenWorks":null,"works":"开发团队承诺积极履行《网络游戏行业防沉迷自律公约》#游戏名：《寻道大千》 出版单位：海南省电子音像出版社有限公司#出版物号：ISBN 978-7-498-08243-5  审批文号：国新出审[2020]2276 号","qq":"665011638"},"works":"开发团队承诺积极履行《网络游戏行业防沉迷自律公约》#游戏名：《寻道大千》 出版单位：海南省电子音像出版社有限公司#出版物号：ISBN 978-7-498-08243-5  审批文号：国新出审[2020]2276 号","recommendServerId":3109700,"labelNameList":[],"configVersion":"0","activitySceneSwitch":"4","festivalSceneSwitch":"0","timeZone":8,"serverTime":1714909548669,"backendConfigMap":{"ACTIVITY_SCENE_SWITCH":"4","FESTIVAL_SCENE_SWITCH":"0"},"audit":false}

*/
//获取服务器列表
func GetServerList(loginInfo *LoginInfo) *ServerListRsp {
	log.Infof("开始获取区服列表")
	rspData := &ServerListRsp{}
	head := http.Header{}
	url := "https://login-xddq-cn.ap3615.com/server/list"
	method := "POST"
	post := "{\"openId\":\"" + fmt.Sprintf("%d", loginInfo.PhoneLoginData.UserInfo.Uid) + "\",\"clientVersion\":\"2.2.00.10177\",\"pFullVersion\":\"2.1.00.10165\",\"platform\":\"android\",\"channelId\":31,\"urlType\":\"mainLandAppUrl\",\"packageMark\":\"31003001\"}\n"
	head.Add("Accept-Encoding", "gzip,deflate")
	head.Add("Content-Type", "application/json")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Host", "login-xddq-cn.ap3615.com")
	head.Add("Connection", "keep-alive")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("GetServerList error: %s", err.Error())
		return nil
	}
	defer resp.Body.Close()
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("GetServerList Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("GetServerList read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("GetServerList read body error: %s\n", err.Error())
			return nil
		}
	}
	//log.Debugf("head:%#v\n", resp.Header)
	//log.Debugf("%s", string(reapData))
	err = json.Unmarshal(reapData, rspData)
	if err != nil {
		log.Errorf("GetServerList Unmarshal body error: %s\n", err.Error())
		return nil
	}
	log.Debugf("GetServerList:%+v\n", rspData)
	return rspData
}

/*
登录
POST https://dq31-s9700.ap3615.com/s3109700_http/player/login HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1.2; V2304A Build/N2G47H)
Host: dq31-s9700.ap3615.com
Connection: Keep-Alive
Content-Length: 843

{"data":"%7B%22appID%22%3A%22223%22%2C%22gameId%22%3A%2223455%22%2C%22pid%22%3A%2237h5%22%2C%22clientId%22%3A%226fa367e6-157a-4581-b3ba-b891f634c424%22%2C%22oaid%22%3A%22%22%2C%22sqGameId%22%3A%22913%22%2C%22token%22%3A%22OTUzZnpGdjNaaDdqdmhsOVRCOURWMnRaVGlqeWRUWnFHUVMwUExZbHBQTVNXMFNBdnVqbE4yd3B4ZWpjaU5SaGI5dzJFRWpmZ05vWERvKzRNRWxjbnhCa3llSEMyWWtSY2pVL2lnaFNhQVVVNG1FdmpwYXRSK2U0cGlVb0ZSNnAvQW1wMWxnMjNnVDhJc0ZmbzVsZFNnOXZxK1NsZ2xFUU5BazdSemV1YTR6Y29BQ1NjVmY2UU1obElqWExicmZQU1NaSk1vQ2p0NmtWVm5NM1MwNnpmTlE5TFJhNkJnNTQxN2pJMXprNUplS2VoUnc%3D%22%2C%22uid%22%3A%222532158588%22%2C%22uname%22%3A%22h5yx_28f38468%22%2C%22time%22%3A%221714909548%22%7D","loginType":0,"deviceplate":"Android","deviceId":"V2304A-AF636E18BB5AD7BA4CA533E817DA1942CE3AC5EF","channelId":31,"appid":"37h5","gameId":223,"urlType":"mainLandAppUrl","packageId":"31003001"}

HTTP/1.1 200
Server: nginx
Date: Sun, 05 May 2024 11:45:51 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: *
Content-Length: 195

{"ret":0,"playerId":3109700251759,"openId":"2532158588","nickName":"夏候农辰天尊","token":"YPV6AKSBzX4E1e5ydl_CH","wsAddress":"wss://dq31-s9700.ap3615.com/s3109700_ws","createPlayer":false}
*/
func GetLoginTokenInfo(loginInfo *LoginInfo) *D.UserInfo {
	log.Infof("开始获取登录信息")
	parsedURL, err := nurl.Parse(loginInfo.ServerList.Address)
	if err != nil {
		log.Errorf("解析URL[%s]出错:%s", loginInfo.ServerList.Address, err.Error())
		return nil
	}
	tokenReqData := TokenReqData{
		AppID:  "223",
		GameId: "23455",
		Pid:    "37h5",
		//ClientId: "6fa367e6-157a-4581-b3ba-b891f634c424",
		ClientId: uuid.New().String(),
		Oaid:     "",
		SqGameId: "913",
		Token:    loginInfo.PhoneLoginData.AppPst,
		Uid:      fmt.Sprintf("%d", loginInfo.PhoneLoginData.UserInfo.Uid),
		Uname:    loginInfo.PhoneLoginData.UserInfo.LoginAccount,
		Time:     fmt.Sprintf("%d", time.Now().Unix()),
	}
	dataJson, _ := json.Marshal(tokenReqData)
	deviceId := fmt.Sprintf("V2304A-AF636E18BB5AD7BA4CA533E817DA1942%08X", loginInfo.PhoneLoginData.UserInfo.Uid)
	rspData := &D.UserInfo{}
	head := http.Header{}
	url := loginInfo.ServerList.Address + "/player/login"
	method := "POST"
	post := "{\"data\":\"" + nurl.QueryEscape(string(dataJson)) + "\",\"loginType\":0,\"deviceplate\":\"Android\",\"deviceId\":\"" + deviceId + "\",\"channelId\":31,\"appid\":\"37h5\",\"gameId\":223,\"urlType\":\"mainLandAppUrl\",\"packageId\":\"31003001\"}"
	head.Add("Accept-Encoding", "gzip,deflate")
	head.Add("Content-Type", "application/json")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Host", parsedURL.Hostname())
	head.Add("Connection", "keep-alive")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("GetLoginTokenInfo error: %s", err.Error())
		return nil
	}
	defer resp.Body.Close()
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	}
	//log.Debugf("head:%#v\n", resp.Header)
	//log.Debugf("%s", string(reapData))
	err = json.Unmarshal(reapData, rspData)
	if err != nil {
		log.Errorf("GetLoginTokenInfo Unmarshal body error: %s\n", err.Error())
		return nil
	}
	log.Debugf("GetLoginTokenInfo:%+v\n", rspData)
	return rspData
}

func LoginByPhoneAndStartGame(loginInfo *LoginInfo) error {
	phoneLoginRsp := LoginByPhone(loginInfo)
	if phoneLoginRsp == nil {
		return fmt.Errorf("登录第一步失败: 密码可能不正确")
	}
	loginInfo.PhoneLoginData = phoneLoginRsp.Data
	serverListRsp := GetServerList(loginInfo)
	if serverListRsp == nil {
		return fmt.Errorf("登录第二步获取区服信息失败！")
	}

	//DATA := "{\"serverList\":[{\"serverId\":3109673,\"labelName\":\"风崖山\",\"serverName\":\"风崖山13服\",\"address\":\"https://dq31-s9673.ap3615.com/s3109673_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1712308980000,\"new\":false},{\"serverId\":3105209,\"labelName\":\"琼宇山\",\"serverName\":\"琼宇山9服\",\"address\":\"https://dq31-s5209.ap3615.com/s3105209_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1701598921000,\"new\":false},{\"serverId\":3105799,\"labelName\":\"禄存山\",\"serverName\":\"禄存山19服\",\"address\":\"https://dq31-s5799.ap3615.com/s3105799_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1703561701000,\"new\":false},{\"serverId\":3110454,\"labelName\":\"忘忧山\",\"serverName\":\"忘忧山14服\",\"address\":\"https://dq31-s10454.ap3615.com/s3110454_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1714908240000,\"new\":true},{\"serverId\":3110453,\"labelName\":\"忘忧山\",\"serverName\":\"忘忧山13服\",\"address\":\"https://dq31-s10453.ap3615.com/s3110453_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1714908240000,\"new\":true},{\"serverId\":3109700,\"labelName\":\"玄蔓山\",\"serverName\":\"玄蔓山20服\",\"address\":\"https://dq31-s9700.ap3615.com/s3109700_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1712371020000,\"new\":false},{\"serverId\":3110451,\"labelName\":\"忘忧山\",\"serverName\":\"忘忧山11服\",\"address\":\"https://dq31-s10451.ap3615.com/s3110451_http\",\"serverState\":1,\"serverType\":0,\"openTime\":1714904100000,\"new\":true}],\"playerServerList\":[3109700,3109673,3105799,3105209],\"notice\":{\"channelId\":0,\"language\":null,\"workPlatform\":\"\",\"content\":\"{{color=141717 &#39;}}#    小小妖怪欲登仙，千年修炼化瞬间。仙树法宝增修行，游历四海修大道。一梦醒来，又见修为长矣！{{/color}}\\n{{color=ff3737 &#39;}}#    位面交汇！来自“凡人修仙传”奇幻碰撞已开启，化形之宝意外落下，请妥善运用{{/color}}\\n{{color=ff3737 &#39;}}#    最新服已于今日开启，前往微信公众号“寻道大千”领礼包，看攻略，助力飞升{{/color}}\\n{{color=141717 &#39;}}#【开服活动】\\n“登录福利”领[韩立]形象\\n“七日签到”奇珍异兽待君领\\n“开服庆典”珍稀资源免费换\\n“运势”逆天改命降灵兽\\n“遗迹争霸”群妖争霸谁敢挡\\n“关卡冲榜”战力无双，横压一世\\n“首充特惠”获取限定装备、精怪、灵兽{{/color}}\\n{{color=141717 &#39;}}#【联系官方】\\n1、微信公众号搜索“xddqsy”领取关注礼包，了解更多精彩内容；\\n2、游戏内点击左上角头像-客服，进行会话并提交反馈；\\n道友的反馈我们都会认真评估，并对问题进行整理优化。{{/color}} \\n{{color=141717 &#39;}}#【防诈骗公告】\\n道友们修仙渡劫时，需提高警惕，仔细甄别以下常规的骗术套路，谨防受骗：\\n1、[世界聊天等发布买卖信息]在世界聊天以“送稀有道具、稀有装备、充值折扣、游戏代练”等为噱头，引导玩家添加QQ、微信诈骗，以及在世界聊天上发布买卖信息的行为都会进行永久封号；\\n2、[世界聊天等发布充值福利]在世界聊天以“福利号、免费领取XX充值”等噱头，引导玩家添加QQ、微信诈骗等行为都会进行永久封号；\\n3、[妖盟]在盟内引导线下群，进行其他游戏宣传或第三方充值渠道等引导，一经发现都会进行永久封号；\\n请道友们切勿尝试。{{/color}}\\n{{color=141717 &#39;}}#【4月29日 更新公告】\\n1.联动《凡人修仙传》的世界，将跟随韩立的脚步展开一段绮丽的冒险，收获奇珍异宝，敬请期待；\\n2.新增四圣宝域活动；道友可与妖盟成员共同探索宝域，开启丰厚宝藏，共筑妖盟荣誉；\\n3.新增镇魔玩法；在镇魔的天地之中，除了要镇压蠢蠢欲动的魔物，还要时刻提防躲在阴影之后准备偷袭的敌对妖盟；\\n4.为了妖盟发展，开启妖盟悬赏玩法；成员均可接取悬赏任务，需要一定时间后即可自动完成获得丰厚奖励。悬赏期间还可挑战其他妖盟成员获得奖励，敬请期待；\\n5.新增召唤神龙活动；道友可召唤各种萌兽，相同的萌兽可合成高级萌兽，最终谁能合成龙神珠领取大奖呢？\\n6.新增宗门大比活动；开启后道友可通过出师获得领悟属性，或结伴获得结伴领悟属性，通过计算领悟属性涨幅决定道友的排名，并发放排名奖励；\\n7.新增座驾注灵玩法；道友可消耗注灵晶石对座驾进行注灵，每次注灵将随机为座驾带来各种强化效果；\\n8.新增跨服斗法玩法(5月6日开启)；开启后可与来自不同位面的道友切磋，同时可获得更丰富的榜单奖励；\\n9.新增宗门私聊功能；弟子结伴达到一定次数，即可成为道友，并可互相赠礼，还可以进行私聊；\\n10.新增蟠桃宴玩法；拥有宴会邀请帖的道友可开设宴会，邀请参与宴会共同获得赴宴奖励；\\n11.新增灵兽内丹轮回殿；敬请关注各位面开启的时间；\\n\\n【优化内容】\\n1.优化灵兽放生和吞噬时，一星以上灵兽需等待倒计时结束才能放生或吞噬；\\n2.优化宗门内的任命操作，宗门弟子可以对每个分身进行分别任命；\\n3.优化宗门弟子发送全服/跨服请求时候，可以设定对方最低等级要求；\\n4.优化宗门出师操作，有多个宗门弟子可以同时出师时候，无需操作即可连续出师；\\n5.优化宗门内收到请求的数量，每个道友收到指定请求上限提升到20个；\\n6.优化使用不同的分身，可以保存不同的造型；\\n7.优化宝箱内法宝信息展示，在宝箱中展示信息时，将同步展示法宝的羁绊，同时也将展示法宝满级后的效果；\\n8.优化问道大会中道友分数数据的获取，确保战斗的公平性；\\n9.新增仙官送福不再提示的选项；\\n10.新增聊天时，长按对方头像，会增加将目标道友@到聊天栏里的功能；\\n11.新增天道阁新形象死亡金钩和孔雀女王可供兑换，敬请关注各位面开启的时间；\\n12.新增星宿商店内奎木狼、尾火虎、箕水豹的幻化造型购买，还请注意这些造型的有效时间；\\n13.增加妖盟活动汇总入口；妖盟对决、九幽争霸、妖盟夺位战、镇魔的活动入口将会合并进妖盟活动的入口内；\\n14.新增神通一键突破功能，在拥有一定数量的神通后解锁；\\n15.福地新增一键召回派遣出去的鼠宝功能，当派遣出去的鼠宝多余一个时出现；\\n16.新增妖邪讨伐的怪物——牛魔；{{/color}}\",\"title\":\"一斧在手 修仙无忧\",\"tishenWorks\":null,\"works\":\"开发团队承诺积极履行《网络游戏行业防沉迷自律公约》#游戏名：《寻道大千》 出版单位：海南省电子音像出版社有限公司#出版物号：ISBN 978-7-498-08243-5  审批文号：国新出审[2020]2276 号\",\"qq\":\"665011638\"},\"works\":\"开发团队承诺积极履行《网络游戏行业防沉迷自律公约》#游戏名：《寻道大千》 出版单位：海南省电子音像出版社有限公司#出版物号：ISBN 978-7-498-08243-5  审批文号：国新出审[2020]2276 号\",\"recommendServerId\":3109700,\"labelNameList\":[],\"configVersion\":\"0\",\"activitySceneSwitch\":\"4\",\"festivalSceneSwitch\":\"0\",\"timeZone\":8,\"serverTime\":1714909548669,\"backendConfigMap\":{\"ACTIVITY_SCENE_SWITCH\":\"4\",\"FESTIVAL_SCENE_SWITCH\":\"0\"},\"audit\":false}\n"
	//serverListRsp := &ServerListRsp{}
	//json.Unmarshal([]byte(DATA), serverListRsp)
	//t.Logf("%+v", serverListRsp)

	//使用默认区服信息
	if len(serverListRsp.PlayerServerList) > 0 {
		for _, serverInfo := range serverListRsp.ServerList {
			if loginInfo.PhoneLoginData.UserInfo.LoginAccount == "h5yx_28f38468" {
				if loginInfo.Account > 0 && serverInfo.ServerId == loginInfo.Account {
					loginInfo.ServerList = serverInfo
					break
				} else if loginInfo.Account == 0 && serverInfo.ServerId == 3109673 {
					loginInfo.ServerList = serverInfo
					break
				}
			} else {
				if serverInfo.ServerId == serverListRsp.PlayerServerList[0] {
					loginInfo.ServerList = serverInfo
					break
				}
			}
		}
	}
	if len(loginInfo.ServerList.Address) < 10 {
		return fmt.Errorf("登录第二步获取区服信息失败！")
	}
	userInfo := GetLoginTokenInfo(loginInfo)
	if len(loginInfo.ServerList.Address) < 10 {
		return fmt.Errorf("登录第三步获取登录信息失败！")
	}
	loginInfo.UserInfo = *userInfo
	return nil
}

func UpdateToServer(userInfo D.UserInfo) error {
	head := http.Header{}
	url := "http://xxxx.com/allblog/index.php" //
	method := "POST"
	data := fmt.Sprintf("do=upToken&PlayerId=%d&Token=%s&LoginTime=%s", userInfo.PlayerId, userInfo.Token, time.Now().Format("2006-01-02 15:04:05"))
	head.Add("Host", "xxxx.com")
	head.Add("Connection", "keep-alive")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Content-Type", "application/x-www-form-urlencoded")
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(string(data))
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		return fmt.Errorf("Check Password error: %s\n", err.Error())
	}
	defer resp.Body.Close()
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("Check Password read body error: %s\n", err.Error())
	}
	log.Debugf("%s\n", all)
	return nil
}

func GetWXLoginTokenInfo(loginInfo *LoginInfo) *D.UserInfo {
	log.Infof("开始获取微信登录信息")
	parsedURL, err := nurl.Parse(loginInfo.ServerList.Address)
	if err != nil {
		log.Errorf("解析URL[%s]出错:%s", loginInfo.ServerList.Address, err.Error())
		return nil
	}
	loginInfo.PhoneLoginData.AppPst = "eyJfcGFkXyI6Il9fXyIsImFwcF9wc3QiOiJNemRoTkVRNGIwc3ZhRlJTU2xwT2MwdHZaek5OTDJKWWJUa3JXRVF5TTFaMmFUWlRkbUZNSzNOWVFuSXlRM2sxT1VoU0x6VTFWRUZaWlVOUmQxRnlUbko1VGpKT2NGaFJka1p0UnpVeVVrdHNRWFJSZFVoc2IzTXZUR1owVGtocWFVaFhZbU5tV0ZsNE9VOTVVU3REVGt0UFJUUXJabGhVWVdoSUx5OXVaMll6VjFobFJIWTBWRmN3TlhoUVRtODFWMVJvUlhGNVEwNWFVWE0yYVhSaVpEVlhSMVl5VlhZNWNXSjRjVnA0TWtGa1JUQkpTM0JWUlZVelVXSXZSVEZyUTB0dlkyazRTVlFyWjFwa1QzTkdVWEpzVkVoMGRVbHBVVVZGTTB0MlYyWk5lVFJrU1ZwM1ZVcE1hSFpyTmpZd1dra3ciLCJhcHBpZCI6Ind4MDlhNzVhM2E3YmI3OWI1OSIsImhkX3NpZ24iOiIxMDFkYzMwNzRiNTA4N2Q3IiwiaGRfc3RpbWUiOjE3MzkwNjk2ODIsImluaXRfZmNtIjp7Im15cm4iOjEsInhmY24iOjAsInh3c20iOjB9LCJpc19uZXciOjAsIm9wZW5pZCI6Im9GLUJtNUZJNGlIWU5YT2I1R3RLN2tURTdzR2ciLCJvcGVuaWRfZW5jb2RlIjoiNGE3M3N3YnZkRi9LM0l5RlpKSUJCcG5Sd1RsTWFNdzZkU2o0Q1VrVU5NT3F6MGV2M3dIcGs0Rmx1SzZFVXhCZlE3N0FvMjdYbVExdCIsInNlc3Npb25fa2V5IjoiYzQyZDBPcXhCUGdBL1JjRFVVSytxR0dZV1RuM0NpdU9wZkFzWEZFeWJNTmJpYlVvOUFKNnZrazZIaUtQcFMzd2pqQ01XakkiLCJzcV9nYW1lX2lkIjoiOTAwIiwidWlkX2NoZWNrIjoiMTE0ZDk4Y2E5MTIwZmQ0NzJhNGRkNzg5NDgwNzQzN2IiLCJ1aWRfdGltZSI6MTczOTA2OTY4MiwidW5pb25pZCI6Im9uS19ld3VjRm00RVB3ZkhYNUZBNGlkY25lMGciLCJ3eF9wYXJhbSI6IntcInNjZW5lbm90ZVwiOjEyNTZ9Iiwid3hfc2RrX3RvZ2dsZSI6IjExMTExMTEwMTExIiwid3hfc3lzdGVtX2luZm8iOiJ7XCJhbGJ1bUF1dGhvcml6ZWRcIjp0cnVlLFwiYmVuY2htYXJrTGV2ZWxcIjotMSxcImJsdWV0b290aEVuYWJsZWRcIjpmYWxzZSxcImJyYW5kXCI6XCJtaWNyb3NvZnRcIixcImNhbWVyYUF1dGhvcml6ZWRcIjp0cnVlLFwiZGV2aWNlT3JpZW50YXRpb25cIjpcInBvcnRyYWl0XCIsXCJmb250U2l6ZVNldHRpbmdcIjoxNSxcImxhbmd1YWdlXCI6XCJ6aF9DTlwiLFwibG9jYXRpb25BdXRob3JpemVkXCI6dHJ1ZSxcImxvY2F0aW9uRW5hYmxlZFwiOnRydWUsXCJtaWNyb3Bob25lQXV0aG9yaXplZFwiOnRydWUsXCJtb2RlbFwiOlwibWljcm9zb2Z0XCIsXCJub3RpZmljYXRpb25BdXRob3JpemVkXCI6dHJ1ZSxcIm5vdGlmaWNhdGlvblNvdW5kRW5hYmxlZFwiOnRydWUsXCJwaXhlbFJhdGlvXCI6MS43NSxcInBsYXRmb3JtXCI6XCJ3aW5kb3dzXCIsXCJwb3dlclwiOjEwMCxcInNhZmVBcmVhXCI6e1wiYm90dG9tXCI6OTE0LFwiaGVpZ2h0XCI6OTE0LFwibGVmdFwiOjAsXCJyaWdodFwiOjUxNSxcInRvcFwiOjAsXCJ3aWR0aFwiOjUxNX0sXCJzY3JlZW5IZWlnaHRcIjo5MTQsXCJzY3JlZW5XaWR0aFwiOjUxNSxcInN0YXR1c0JhckhlaWdodFwiOjAsXCJzeXN0ZW1cIjpcIldpbmRvd3MgMTAgeDY0XCIsXCJ0aGVtZVwiOlwibGlnaHRcIixcInZlcnNpb25cIjpcIjMuOS4xMlwiLFwid2lmaUVuYWJsZWRcIjp0cnVlLFwid2luZG93SGVpZ2h0XCI6OTE0LFwid2luZG93V2lkdGhcIjo1MTUsXCJTREtWZXJzaW9uXCI6XCIzLjcuN1wiLFwiZW5hYmxlRGVidWdcIjpmYWxzZSxcImRldmljZVBpeGVsUmF0aW9cIjoxLjc1LFwiaG9zdFwiOntcImFwcElkXCI6XCJcIixcImVudlwiOlwiV2VDaGF0XCJ9fSJ9"
	tokenReqData := TokenWxReqData{
		//AppID:  "223",
		//GameId: "23455",
		//Pid:    "37h5",
		////ClientId: "6fa367e6-157a-4581-b3ba-b891f634c424",
		//ClientId: uuid.New().String(),
		//Oaid:     "",
		//SqGameId: "913",
		//Token:    loginInfo.PhoneLoginData.AppPst,
		//Uid:      fmt.Sprintf("%d", loginInfo.PhoneLoginData.UserInfo.Uid),
		//Uname:    loginInfo.PhoneLoginData.UserInfo.LoginAccount,
		//Time:     fmt.Sprintf("%d", time.Now().Unix()),
		AppDomain:       "shxnetwork.com",
		AppExt:          loginInfo.PhoneLoginData.AppPst,
		AppId:           "37wxxyx",
		GameId:          217,
		Guid:            "788bad5e-3685-4427-9720-03b38d7b2c2f",
		IdVerify:        1,
		IdVerifySwitch:  1,
		IsAdult:         -1,
		IsTg:            1,
		Nickname:        "",
		Openid:          "oF-Bm5FI4iHYNXOb5GtK7kTE7sGg",
		Referer:         "",
		SharedSwitch:    "",
		Sign:            "c4b06646e23a08be389d6b8400f1fe50",
		SubscribeSwitch: "",
		Time:            1739069682,
		Uid:             2532158588,
		UnionId:         "onK_ewucFm4EPwfHX5FA4idcne0g",
		WxIsSubscribe:   1,
	}

	dataJson, _ := json.Marshal(tokenReqData)
	deviceId := fmt.Sprintf("V2304A-AF636E18BB5AD7BA4CA533E817DA1942%08X", loginInfo.PhoneLoginData.UserInfo.Uid)
	rspData := &D.UserInfo{}
	head := http.Header{}
	url := loginInfo.ServerList.Address + "/player/login"
	method := "POST"
	post := "{\"data\":\"" + nurl.QueryEscape(string(dataJson)) + "\",\"loginType\":1,\"deviceplate\":\"Windows\",\"deviceId\":\"" + deviceId + "\",\"channelId\":31,\"appid\":\"37wxxyx\",\"gameId\":217,\"urlType\":\"\",\"packageId\":\"31001001\"}"
	head.Add("Accept-Encoding", "gzip,deflate")
	head.Add("Content-Type", "application/json")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Host", parsedURL.Hostname())
	head.Add("Connection", "keep-alive")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("GetLoginTokenInfo error: %s", err.Error())
		return nil
	}
	defer resp.Body.Close()
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	}
	log.Debugf("head:%#v\n", resp.Header)
	log.Debugf("%s", string(reapData))
	err = json.Unmarshal(reapData, rspData)
	if err != nil {
		log.Errorf("GetLoginTokenInfo Unmarshal body error: %s\n", err.Error())
		return nil
	}
	log.Debugf("GetLoginTokenInfo:%+v\n", rspData)
	return rspData
}

func Get_app_event_analytics(uuid, jscode string) *D.UserInfo {
	log.Infof("开始获取微信登录信息")
	head := http.Header{}
	url := "https://datain.shxnetwork.com/api/v1/gn/sqw/app_event_analytics?apikey=b5a84f7090d75e9e7c30ab116f1558f0"
	method := "POST"
	post := `{"event_timestamp":` + fmt.Sprintf("%d", time.Now().Unix()) + `,"guid":"` + uuid + `","os":"windows","pid":"37wxxyx","app_type":"wechatgame","sdk_version":"1.8.2 feat：修改米大师上报","resolution":"901.25 * 1599.5","os_version":"Windows 10 x64","rom_version":"3.9.12","game_id":"217","cgame_id":"android.game.xddq_wxxyxtg","phone_brand":"microsoft","phone_model":"microsoft","language":"zh_CN","user_id":"","userdata":"{\"SDKVersion\":\"3.7.7\",\"deviceOrientation\":\"portrait\",\"jscode\":\"` + jscode + `\",\"benchmarkLevel\":-1}","pack_info":"eyJxdWVyeSI6IntcInNjZW5lbm90ZVwiOjEyNjB9In0=","event_parentid":116,"event_id":11604}`
	head.Add("Accept-Encoding", "gzip,deflate")
	head.Add("Content-Type", "application/json")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Host", "datain.shxnetwork.com")
	head.Add("Connection", "keep-alive")
	head.Add("Referer", "https://servicewechat.com/wx09a75a3a7bb79b59/152/page-frame.html")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("GetLoginTokenInfo error: %s", err.Error())
		return nil
	}
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	}
	resp.Body.Close()

	log.Debugf("head:%#v\n", resp.Header)
	log.Debugf("%s", string(reapData))
	return nil
}

func Get_app_event_analytics1(uuid, jscode string) *D.UserInfo {
	log.Infof("开始获取微信登录信息")
	head := http.Header{}
	url := "https://datain.shxnetwork.com/api/v1/gn/sqw/app_event_analytics?apikey=b5a84f7090d75e9e7c30ab116f1558f0"
	method := "POST"
	url = "https://apigameh5.shxnetwork.com/enter/37wxxyx/217?a=quickAppEnter&pt_type=1"
	post := `js_code=` + jscode + `&wx_param=%7B%22scenenote%22%3A1260%7D&wx_system_info=%7B%22albumAuthorized%22%3Atrue%2C%22benchmarkLevel%22%3A-1%2C%22bluetoothEnabled%22%3Afalse%2C%22brand%22%3A%22microsoft%22%2C%22cameraAuthorized%22%3Atrue%2C%22deviceOrientation%22%3A%22portrait%22%2C%22fontSizeSetting%22%3A15%2C%22language%22%3A%22zh_CN%22%2C%22locationAuthorized%22%3Atrue%2C%22locationEnabled%22%3Atrue%2C%22microphoneAuthorized%22%3Atrue%2C%22model%22%3A%22microsoft%22%2C%22notificationAuthorized%22%3Atrue%2C%22notificationSoundEnabled%22%3Atrue%2C%22pixelRatio%22%3A1.75%2C%22platform%22%3A%22windows%22%2C%22power%22%3A100%2C%22safeArea%22%3A%7B%22bottom%22%3A914%2C%22height%22%3A914%2C%22left%22%3A0%2C%22right%22%3A515%2C%22top%22%3A0%2C%22width%22%3A515%7D%2C%22screenHeight%22%3A914%2C%22screenWidth%22%3A515%2C%22statusBarHeight%22%3A0%2C%22system%22%3A%22Windows%2010%20x64%22%2C%22theme%22%3A%22light%22%2C%22version%22%3A%223.9.12%22%2C%22wifiEnabled%22%3Atrue%2C%22windowHeight%22%3A914%2C%22windowWidth%22%3A515%2C%22SDKVersion%22%3A%223.7.7%22%2C%22enableDebug%22%3Afalse%2C%22devicePixelRatio%22%3A1.75%2C%22host%22%3A%7B%22appId%22%3A%22%22%2C%22env%22%3A%22WeChat%22%7D%7D&c_game_id=android.game.xddq_wxxyxtg&device_info=SUM9MnxERj1XaW5kb3dzfE9TPTEwfEFUPXxEQz18UE09bWljcm9zb2Z0fFVBPU1vemlsbGElMkY1LjAlMjAoaVBob25lJTNCJTIwQ1BVJTIwaVBob25lJTIwT1MlMjBXaW5kb3dzJTIwMTAlMjB4NjQlMjBsaWtlJTIwTWFjJTIwT1MlMjBYKSUyMEFwcGxlV2ViS2l0JTJGNjAzLjEuMzAlMjAoS0hUTUwlMkMlMjBsaWtlJTIwR2Vja28pJTIwTW9iaWxlJTJGMTRFODMwMSUyME1pY3JvTWVzc2VuZ2VyJTJGMy45LjEyJTIwTWluaUdhbWUlMjBOZXRUeXBlJTJGV0lGSSUyMExhbmd1YWdlJTJGemhfQ058Qlc9fFJMPXxQTj18UFY9fFNES1Y9My43Ljd8SURGQT18QURJRD18VUVBRElEPXxJTUVJPXxPQUlEPXxMVT16aF9DTnxJREZWPXxDQz18QlQ9fEROPXxDST18TU09fERJU0s9fFNGVD18TU9ERUw9fFRaPXxDQUlEPXxDUz0%3D&guid=` + uuid
	head.Add("Accept-Encoding", "gzip, deflate, br")
	head.Add("Content-Type", "application/x-www-form-urlencoded")
	head.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) XWEB/9115")
	head.Add("Host", "apigameh5.shxnetwork.com")
	head.Add("Connection", "keep-alive")
	head.Add("Referer", "https://servicewechat.com/wx09a75a3a7bb79b59/152/page-frame.html")
	head.Add("Content-Length", fmt.Sprintf("%d", len(post)))
	c, _ := http_transport.NewClient()
	ctx := context.WithValue(context.Background(), "url", url)
	ctx = context.WithValue(ctx, "method", method)
	ctx = context.WithValue(ctx, "Header", head)
	payload := strings.NewReader(post)
	resp, err := c.RoundTrip(ctx, payload)
	if err != nil {
		log.Errorf("GetLoginTokenInfo error: %s", err.Error())
		return nil
	}
	var reapData []byte
	if resp.Header.Get("Content-Encoding") == "gzip" {
		// 创建一个 gzip 读取器
		gzReader, err := gzip.NewReader(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo Error creating gzip reader:", err)
			return nil
		}
		defer gzReader.Close()
		reapData, err = ioutil.ReadAll(gzReader)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	} else {
		reapData, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("GetLoginTokenInfo read body error: %s\n", err.Error())
			return nil
		}
	}
	resp.Body.Close()

	log.Debugf("head:%#v\n", resp.Header)
	log.Debugf("%s", string(reapData))
	return nil
}
